<template>
    <div class="koi-flex">
        <KoiCard>
            <!-- 搜索条件 -->
            <el-form v-show="showSearch" :inline="true">
                <el-form-item label="文章标题" prop="title">
                    <el-input placeholder="请输入文章标题" v-model="searchParams.title" clearable style="width: 240px"
                        @keyup.enter.native="handleListPage"></el-input>
                </el-form-item>
                <el-form-item label="文章标签" prop="title">
                    <el-select v-model="searchParams.tag" filterable placeholder="请输入标签内容" style="width: 240px"
                        :filter-method="getTag" clearable>
                        <el-option v-for="item in options" :key="item.categoryId" :label="item.categoryName"
                            :value="item.categoryName" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
                    <el-button type="danger" icon="refresh" plain v-debounce="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- 表格头部按钮 -->
            <el-row :gutter="10">
                <el-col :span="1.5" v-auth="['system:role:add']">
                    <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
                </el-col>
                <el-col :span="1.5" v-auth="['system:role:delete']">
                    <el-button type="danger" icon="delete" plain @click="handleBatchDelete()"
                        :disabled="multiple">删除</el-button>
                </el-col>
                <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
            </el-row>

            <div class="h-20px"></div>
            <!-- 数据表格 -->
            <el-table v-loading="loading" border :data="tableList" empty-text="暂时没有数据哟🌻"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" prop="articleId" width="60px" align="center" type="index"></el-table-column>
                <el-table-column label="文章标题" prop="title" width="120px" :show-overflow-tooltip="true"
                    align="center"></el-table-column>
                <el-table-column label="文章头图" prop="titleImg" width="120px" align="center">
                    <template #default="{ row }">
                        <el-image size="large" fit="contain" :src="row.titleImg" />
                    </template>
                </el-table-column>
                <el-table-column label="文章内容" prop="content" width="120px" :show-overflow-tooltip="true" align="center">
                    <template #default="{ row }">
                        <el-link type="primary" @click="openDia(row)">查看文章</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="标签" prop="tags" align="center" show-overflow-tooltip>
                    <template #="{ row }">
                        <el-tag v-for="(tag, index) in row.tags" class="mr-2" :key="index" type="primary">
                            {{ tag }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="130px" align="center"></el-table-column>
                <el-table-column label="创建时间" prop="updateTime" width="130px" align="center"></el-table-column>
                <el-table-column label="操作" align="center" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-tooltip content="修改🌻" placement="top">
                            <el-button type="primary" icon="Edit" circle plain @click="handleUpdate(row)"
                                v-auth="['system:role:update']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除🌻" placement="top">
                            <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"
                                v-auth="['system:role:delete']"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <div class="h-20px"></div>
            <!-- 分页 -->
            <el-pagination background v-model:current-page="searchParams.page" v-model:page-size="searchParams.pageSize"
                v-show="total > 0" :page-sizes="[10, 20, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleListPage" @current-change="handleListPage" />

            <!-- 添加 OR 修改 -->
            <KoiDrawer ref="koiDrawerRef" :title="title" @koiConfirm="handleConfirm" @koiCancel="handleCancelDrawer"
                :loading="confirmLoading">
                <template #content>
                    <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
                        <el-row>
                            <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="文章标题" prop="title">
                                    <el-input v-model="form.title" placeholder="请输入文章标题" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="文章头图" prop="titleImg">
                                    <KoiUploadImage v-model:imageUrl="form.titleImg" :fileSize="5">
                                        <template #content>
                                            <el-icon>
                                                <Avatar />
                                            </el-icon>
                                            <span>请上传头图</span>
                                        </template>
                                        <template #tip>图片最大为 5M</template>
                                    </KoiUploadImage>
                                </el-form-item>
                            </el-col>
                            <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="文章标签" prop="tags">
                                    <template #default>
                                        <div class="tag-container">
                                            <el-tag v-for="tag in form.tags" :key="tag" closable class="mr-2"
                                                type="primary" @close="handleClose(tag)">
                                                {{ tag }}
                                            </el-tag>
                                            <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue"
                                                placeholder="输入标签后回车或失焦确认" size="small" style="width: 150px"
                                                @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                                            <el-button v-else class="button-new-tag" size="small" @click="showInput">
                                                + 新增标签
                                            </el-button>
                                        </div>
                                    </template>
                                </el-form-item>
                            </el-col>
                            <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                                <el-form-item label="文章" prop="content">
                                    <el-link type="primary" :underline="false" @click="openDiaToUpdate">文章内容</el-link>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </template>
            </KoiDrawer>
            <!-- 展示文章内容 -->
            <KoiDialog ref="koiDialogRef" :title="dialogTitle" :footerHidden="true" @koiConfirm="handleConfirm"
                @koiCancel="handleCancel" :loading="confirmLoading" width="auto" height="auto">
                <template #content>
                    <v-md-preview v-if="showfooter" :text="text"></v-md-preview>
                    <Mdv3 v-else v-model="form.content"></Mdv3>
                </template>
            </KoiDialog>
        </KoiCard>
    </div>
</template>

<script setup lang="ts" name="rolePage">
import { nextTick, ref, reactive, onMounted } from "vue";
import type { InputInstance } from 'element-plus'
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo, koiMsgSuccess } from "@/utils/koi.ts";
import { getAllArticle, getArticleById, updateArticle, addArticle, deleteArticle } from "@/api/system/article";
import { getAllTag } from "@/api/system/tag";
import debounce from 'lodash/debounce'
import Mdv3 from "@/components/mdv3/mdv3.vue";
import { getAllInfo } from "@/utils/storage";
const user = getAllInfo()
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>();
// tag
const options = ref()
// dialog
const koiDialogRef = ref()
// text
const text = ref()
// inputVisible
const inputVisible = ref(false)
const inputValue = ref('')
const InputRef = ref<InputInstance>()
// 是否展示弹窗的确认
const showfooter = ref(true)
// dialog 标题
const dialogTitle = ref("文章内容")
// 查询参数
const searchParams = ref({
    page: 1, // 第几页
    pageSize: 10, // 每页显示多少条
    title: "",
    tag: ''
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
    searchParams.value = {
        page: 1,
        pageSize: 10,
        title: "",
        tag: ""
    };
};
// 打开弹窗
const openDia = (row: any) => {
    text.value = row.content
    koiDialogRef.value.koiOpen()
    showfooter.value = true
    dialogTitle.value = "文章内容"
}
// 打开展示框
const openDiaToUpdate = () => {
    koiDialogRef.value.koiOpen()
    showfooter.value = false
    dialogTitle.value = "文章修改"
}
// const showInput = () => {
//     selectVisible.value = true;
//     nextTick(() => {
//         // 聚焦到选择框的输入部分
//         setTimeout(() => {
//             const inputEl = InputRef.value?.$el?.querySelector('input');
//             inputEl?.focus();
//         }, 0);
//     });
// }
const handleClose = (tag: string) => {
    form.value.tags.splice(form.value.tags.indexOf(tag), 1)
}
// 标签输入处理逻辑
const handleInputConfirm = () => {
    if (inputValue.value.trim()) {
        if (!form.value.tags) {
            form.value.tags = [];
            form.value.tags.push(inputValue.value.trim());
        } else
            // 检查重复标签
            if (!form.value.tags.includes(inputValue.value.trim())) {
                form.value.tags.push(inputValue.value.trim())
                inputValue.value = ''
            } else {
                koiMsgWarning("该标签已存在！")
            }
    }
    inputVisible.value = false
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value?.focus()
    })
}


/** 搜索 */
const handleSearch = () => {
    searchParams.value.page = 1;
    handleListPage();
};

/** 重置 */
const resetSearch = () => {
    console.log("重置搜索");
    resetSearchParams();
    handleListPage();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
    total.value = 9;
    try {
        loading.value = true;
        tableList.value = []; // 重置表格数据
        const res: any = await getAllArticle(searchParams.value);
        console.log("文章数据表格数据->", res.data);
        tableList.value = res.data.records;
        total.value = res.data.total;
        loading.value = false;
    } catch (error) {
        console.log(error);
        koiNoticeError("数据查询失败，请刷新重试🌻");
    }
};
/**
 * 获取tag
 */
const getTag = debounce(async (e: string) => {
    try {
        const res = await getAllTag(e);
        if (res.code == 0) {
            options.value = res.data;
        }
    } catch (error) {
        console.error("获取标签失败", error);
    }
}, 500);
/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
    try {
        const res: any = await getAllArticle(searchParams.value);
        console.log("文章数据表格数据->", res.data);
        tableList.value = res.data.records;
        total.value = res.data.total;
    } catch (error) {
        console.log(error);
        koiNoticeError("数据查询失败，请刷新重试🌻");
    }
};

onMounted(() => {
    // 获取表格数据
    handleListPage();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
    console.log(selection);
    ids.value = selection.map((item: any) => item.articleId);
    single.value = selection.length != 1; // 单选
    multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
    // 打开对话框
    koiDrawerRef.value.koiOpen();
    koiNoticeSuccess("添加🌻");
    // 重置表单
    resetForm();
    // 标题
    title.value = "文章添加";
};

/** 回显数据 */
const handleEcho = async (articleId: any) => {
    if (articleId == null || articleId == "") {
        koiMsgWarning("请选择需要修改的数据🌻");
        return;
    }
    try {
        const res: any = await getArticleById(articleId);
        console.log(res.data);
        form.value = res.data;
    } catch (error) {
        console.log(error);
        koiNoticeError("数据获取失败，请刷新重试🌻");
    }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
    // 打开对话框
    koiDrawerRef.value.koiOpen();
    koiMsgSuccess("修改🌻");
    // 重置表单
    resetForm();
    // 标题
    title.value = "文章修改";
    const articleId = row.articleId;
    if (articleId == null || articleId == "") {
        koiMsgError("请选择需要修改的数据🌻");
    }
    console.log(row);
    // 回显数据
    handleEcho(articleId);
};

// 添加 OR 修改对话框Ref 
const koiDrawerRef = ref();
// 标题
const title = ref("文章内容");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
    articleId: "",
    title: "",
});

/** 清空表单数据 */
const resetForm = () => {
    // 等待 DOM 更新完成
    nextTick(() => {
        if (formRef.value) {
            // 重置该表单项，将其值重置为初始值，并移除校验结果
            formRef.value.resetFields();
        }
    });
    form.value = {
        articleId: "",
        title: "",
        url: "",
        status: "",
        description: ""
    };
};

/** 表单规则 */
const rules = reactive({
    title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
    tags: [{ required: true, message: "文章的tags不能为空", trigger: "blur" }],
    content: [{ required: true, message: "文章内容不能为空", trigger: "blur" }],
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
    if (!formRef.value) return;
    confirmLoading.value = true;
    (formRef.value as any).validate(async (valid: any) => {
        if (valid) {
            console.log("表单ID", form.value.articleId);
            if (form.value.articleId != null && form.value.articleId != "") {
                try {
                    await updateArticle(form.value);
                    koiNoticeSuccess("修改成功🌻");
                    confirmLoading.value = false;
                    koiDrawerRef.value.koiQuickClose();
                    resetForm();
                    handleListPage();
                } catch (error) {
                    console.log(error);
                    confirmLoading.value = false;
                    koiNoticeError("修改失败，请刷新重试🌻");
                }
            } else {
                try {
                    // 设置新增form
                    const addform = {
                        ...form.value,
                        authorNickName: user.nickname,
                    };
                    await addArticle(addform);
                    koiNoticeSuccess("添加成功🌻");
                    confirmLoading.value = false;
                    koiDrawerRef.value.koiQuickClose();
                    resetForm();
                    handleListPage();
                } catch (error) {
                    console.log(error);
                    confirmLoading.value = false;
                    koiNoticeError("添加失败，请刷新重试🌻");
                }
            }
        } else {
            koiMsgError("验证失败，请检查填写内容🌻");
            confirmLoading.value = false;
        }
    });
};

/** 取消 */
const handleCancel = () => {
    koiDialogRef.value.koiClose();
};
const handleCancelDrawer = () => {
    koiDrawerRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
    const articleId = row.articleId;
    if (articleId == null || articleId == "") {
        koiMsgWarning("请选择需要删除的数据🌻");
        return;
    }
    koiMsgBox("您确认需要删除文章标题[" + row.title + "]么？")
        .then(async () => {
            try {
                await deleteArticle([articleId]);
                handleTableData();
                koiNoticeSuccess("删除成功🌻");
            } catch (error) {
                console.log(error);
                koiNoticeError("删除失败，请刷新重试🌻");
                handleTableData();
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};

/** 批量删除 */
const handleBatchDelete = () => {
    if (ids.value.length == 0) {
        koiMsgInfo("请选择需要删除的数据🌻");
        return;
    }
    koiMsgBox("您确认需要进行批量删除么？")
        .then(async () => {
            try {
                await deleteArticle(ids.value);
                handleTableData();
                koiNoticeSuccess("批量删除成功🌻");
            } catch (error) {
                console.log(error);
                koiNoticeError("批量删除失败，请刷新重试🌻");
                handleTableData();
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};
</script>

<style lang="scss" scoped></style>
